package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbCustomerAddressMapper;
import com.bwie.pojo.TbCustomer;
import com.bwie.pojo.TbCustomerAddress;
import com.bwie.service.TbCustomerService;
import com.bwie.mapper.TbCustomerMapper;
import com.bwie.utils.Result;
import com.bwie.vo.CustomerVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author 28242
* @description 针对表【tb_customer(客户常用地址表)】的数据库操作Service实现
* @createDate 2025-07-11 08:58:00
*/
@Service
public class TbCustomerServiceImpl extends ServiceImpl<TbCustomerMapper, TbCustomer>
    implements TbCustomerService{

    @Autowired
    private TbCustomerMapper tbCustomerMapper;

    @Autowired
   private StringRedisTemplate redisTemplate;

    @Autowired
    private TbCustomerAddressMapper tbCustomerAddressMapper;

    @Autowired
    HttpServletRequest request;

    @Override
    public Result CustomerLogin(CustomerVo customerVo) {
        //判断客户账号是否唯一
        QueryWrapper<TbCustomer> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbCustomer::getCustName,customerVo.getCustName());
        TbCustomer tbCustomer = tbCustomerMapper.selectOne(wrapper);
        if (tbCustomer==null){
            return Result.error().setMsg("用户不存在");
        }
        //判断密码是否错误
        if (!tbCustomer.getCustPass().equals(customerVo.getCustPass())){
            return Result.error().setMsg("密码错误");
        }

        String redisToken="token-"+tbCustomer.getCustId();

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("custId", tbCustomer.getCustId())
                .claim("custName", tbCustomer.getCustName())
                .compact();

        redisTemplate.opsForValue().set(redisToken,token,5, TimeUnit.MINUTES);

        tbCustomer.setToken(token);
        tbCustomer.setCustPass(null);


        return Result.ok().setData(tbCustomer);
    }

    @Override
    public Result queryAddressByCustId() {

        String token = request.getHeader("token");
        if (token==null){
            return Result.error().setMsg("请重新登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer custId = body.get("custId", Integer.class);
        if (custId!=null){

           List<TbCustomerAddress> addresses=  tbCustomerAddressMapper.queryAddressByCustId(custId);
            return Result.ok().setData(addresses);
        }
        return null;
    }
}




